﻿using Microsoft.Data.Sqlite;
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace SQLite
{
    /// <summary>
    /// SQLite数据库管理
    /// </summary>
    public class DB
    {
        /// <summary>
        /// 连接字符串
        /// </summary>
        private string _connectionString = "";

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbPath">sqlite文件名（全路径）</param>
        public DB(string dbPath)
        {
            if (string.IsNullOrWhiteSpace(dbPath))
            {
                throw new InvalidOperationException("无效的连接字符串");
            }
            if (!Path.GetExtension(dbPath).ToLower().Equals(".db"))
            {
                throw new InvalidOperationException("数据库的名的扩展名不合法(请以.db结尾)!");
            }
            _connectionString = dbPath;
        }


        #region 增加
        /// <summary>
        /// 增加
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns>返回受影响的行数</returns>
        public int Add<T>(T entity) where T : class
        {
            var builder = GetCreatTableBuilder<T>().Append(GetInsertSql(entity));
            if (builder.Length > 0)
            {
                return ExecuteNonQuery(builder.ToString());
            }
            return 0;
        }

        /// <summary>
        /// 增加
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entitys"></param>
        /// <returns>返回受影响的行数</returns>
        public int Add<T>(IEnumerable<T> entitys) where T : class
        {
            var builder = GetCreatTableBuilder<T>().Append(GetInsertSql(entitys));
            if (builder.Length > 0)
            {
                return ExecuteNonQuery(builder.ToString());
            }
            return 0;
        }

        #endregion

        #region 删除
        /// <summary>
        /// 删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns>返回受影响的行数</returns>
        public int Delete<T>(T entity) where T : class
        {
            var builder = GetDeleteSql(entity);
            if (builder.Length > 0)
            {
                return ExecuteNonQuery(builder.ToString());
            }
            return 0;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entitys"></param>
        /// <returns>返回受影响的行数</returns>
        public int Delete<T>(IEnumerable<T> entitys) where T : class
        {
            var builder = GetDeleteSql(entitys);
            if (builder.Length > 0)
            {
                return ExecuteNonQuery(builder.ToString());
            }
            return 0;
        }
        /// <summary>
        /// 通过主键删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="primaryKeyVaule">主键值</param>
        /// <returns>返回受影响的行数</returns>
        public int Delete<T>(params object[] primaryKeyVaule) where T : class
        {
            if (primaryKeyVaule != null && primaryKeyVaule.Length > 0)
            {
                var primKey = string.Empty;
                var tableName = string.Empty;
                ParseEntity<T>((tableAttribute, columnAttribute) =>
                {
                    if (columnAttribute.IsPk)
                    {
                        tableName = tableAttribute.TableName;
                        primKey = columnAttribute.ColumnName;
                    }
                });

                if (!string.IsNullOrWhiteSpace(primKey) && !string.IsNullOrWhiteSpace(tableName))
                {
                    var sql = $"DELETE FROM {tableName} WHERE {primKey} IN ({string.Join(",", primaryKeyVaule.Select(c => ExType.ConvertSqliteString(c)))});";
                    return ExecuteNonQuery(sql);
                }
            }
            return 0;
        }

        /// <summary>
        /// 自定义条件删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="where">where条件</param>
        /// <returns>返回受影响的行数</returns>
        public int Delete<T>(Expression<Func<T, bool>> where) where T : class
        {
            if (where != null)
            {
                var type = typeof(T);
                var whereMoudel = LambdaToSql.GetWhereSql(where);
                if (whereMoudel != null)
                {
                    if (!string.IsNullOrWhiteSpace(whereMoudel.WhereSql))
                    {
                        var tableAttribute = type.GetTableAttribute();
                        var sql = $"DELETE FROM {tableAttribute.TableName} {whereMoudel.WhereSql};";
                        return ExecuteNonQuery(sql, whereMoudel.Parameters);
                    }
                }
            }
            return 0;
        }

        #endregion

        #region 更新
        /// <summary>
        /// 更新
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns>返回受影响的行数</returns>
        public int Update<T>(T entity) where T : class
        {
            var builder = GetUpdateSql(entity);
            if (builder.Length > 0)
            {
                return ExecuteNonQuery(builder.ToString());
            }
            return 0;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entitys"></param>
        /// <returns>返回受影响的行数</returns>
        public int Update<T>(IEnumerable<T> entitys) where T : class
        {
            var builder = GetUpdateSql(entitys);
            if (builder.Length > 0)
            {
                return ExecuteNonQuery(builder.ToString());
            }
            return 0;
        }
        #endregion

        #region 增加或更新
        /// <summary>
        /// 增加或更新（有则增加无更新）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity">返回受影响的行数</param>
        /// <returns></returns>
        public int AddOrUpdate<T>(T entity) where T : class
        {
            var builder = GetCreatTableBuilder<T>().Append(GetInsertOrUpdateSql(entity));
            if (builder.Length > 0)
            {
                return ExecuteNonQuery(builder.ToString());
            }
            return 0;
        }

        /// <summary>
        /// 增加或更新（有则增加无更新）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entitys">返回受影响的行数</param>
        /// <returns></returns>
        public int AddOrUpdate<T>(IEnumerable<T> entitys) where T : class
        {
            var builder = GetCreatTableBuilder<T>().Append(GetInsertOrUpdateSql(entitys));
            if (builder.Length > 0)
            {
                return ExecuteNonQuery(builder.ToString());
            }
            return 0;
        }
        #endregion

        #region 查询

        #region 原生

        #region 对连接执行 Transact-SQL 语句并返回受影响的行数

        /// <summary>
        /// 对连接执行 Transact-SQL 语句并返回受影响的行数。
        /// </summary>
        /// <param name="commandText">SQL</param>
        /// <param name="dicParameters">字典集合 key：参数名；value：参数值</param>
        /// <returns></returns>
        public int ExecuteNonQuery(string commandText)
        {
            return ExecuteNonQuery(commandText, new List<SqliteParameter>());
        }

        /// <summary>
        /// 对连接执行 Transact-SQL 语句并返回受影响的行数。
        /// </summary>
        /// <param name="commandText">SQL</param>
        /// <param name="dicParameters">字典集合 key：参数名；value：参数值</param>
        /// <returns></returns>
        public int ExecuteNonQuery(string commandText, Dictionary<string, object> dicParameters = null)
        {
            using (var connection = CreateSqliteConnection())
            {
                return connection.ExecuteNonQuery(commandText, dicParameters);
            }
        }


        /// <summary>
        ///  对连接执行 Transact-SQL （参数化查询）语句并返回受影响的行数。
        /// </summary>
        /// <param name="commandText">SQL</param>
        /// <param name="parameters">参数</param>
        /// <returns></returns>
        public int ExecuteNonQuery(string commandText, IEnumerable<SqliteParameter> parameters = null)
        {
            using (var connection = CreateSqliteConnection())
            {
                return connection.ExecuteNonQuery(commandText, parameters);
            }
        }


        #endregion

        #region 对连接执行 Transact-SQL 语句并返回结果集中的第1行第1列,而忽略其他的行和列。

        /// <summary>
        /// 对连接执行 Transact-SQL 语句并返回结果集中的第1行第1列,而忽略其他的行和列。
        /// </summary>
        /// <param name="commandText">SQL</param>
        /// <param name="parameters">参数</param>
        /// <returns></returns>
        public object ExecuteScalar(string commandText, IEnumerable<SqliteParameter> parameters = null)
        {
            using (var connection = CreateSqliteConnection())
            {
                return connection.ExecuteScalar(commandText, parameters);
            }
        }

        /// <summary>
        /// 对连接执行 Transact-SQL 语句并返回结果集中的第1行第1列,而忽略其他的行和列。
        /// </summary>
        /// <param name="commandText">SQL</param>
        /// <param name="parameters">参数集合</param>
        /// <returns></returns>
        public T ExecuteScalar<T>(string commandText, IEnumerable<SqliteParameter> parameters = null)
        {
            using (var connection = CreateSqliteConnection())
            {
                return connection.ExecuteScalar<T>(commandText, parameters);
            }
        }

        /// <summary>
        /// 对连接执行 Transact-SQL 语句并返回结果集中的第1行第1列,而忽略其他的行和列。
        /// </summary>
        /// <param name="commandText">SQL</param>
        /// <returns></returns>
        public T ExecuteScalar<T>(string commandText)
        {
            return ExecuteScalar<T>(commandText, new List<SqliteParameter>());
        }

        /// <summary>
        /// 对连接执行 Transact-SQL 语句并返回结果集中的第1行第1列,而忽略其他的行和列。
        /// </summary>
        /// <param name="commandText">SQL</param>
        /// <param name="dicParameters">字典集合 key：参数名；value：参数值</param>
        /// <returns></returns>
        public T ExecuteScalar<T>(string commandText, Dictionary<string, object> dicParameters = null)
        {
            using (var connection = CreateSqliteConnection())
            {
                return connection.ExecuteScalar<T>(commandText, dicParameters);
            }
        }

        #endregion

        #region 对连接执行 Transact-SQL 语句并返回一个SqliteDataReader对象
        /// <summary>
        /// 对连接执行 Transact-SQL 语句并返回一个SqliteDataReader对象。
        /// </summary>
        /// <param name="commandText">SQL</param>
        /// <param name="parameters">参数</param>
        /// <returns></returns>
        public SqliteDataReader ExecuteReader(string commandText, IEnumerable<SqliteParameter> parameters = null)
        {
            using (var connection = CreateSqliteConnection())
            {
                return connection.ExecuteReader(commandText, parameters);
            }
        }

        /// <summary>
        /// 对连接执行 Transact-SQL 语句并返回一个SqliteDataReader对象。
        /// </summary>
        /// <param name="commandText">SQL</param>
        /// <param name="action">回调</param>
        /// <param name="parameters">参数</param>
        public void ExecuteReader(string commandText, Action<SqliteConnection, SqliteDataReader> action, IEnumerable<SqliteParameter> parameters = null)
        {
            using (var connection = CreateSqliteConnection())
            {
                connection.ExecuteReader(commandText, action, parameters);
            }
        }
        #endregion

        #endregion

        #region 扩展查询

        /// <summary>
        /// 根据主键查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="idValue"></param>
        /// <returns></returns>
        public T FindeById<T>(object idValue)
        {
            var type = typeof(T);
            var tableAtrr = type.GetTableAttribute();
            var colAtrr = type.GetColumnAttribute().FirstOrDefault(c => c.IsPk);
            if (colAtrr == null)
            {
                throw new InvalidOperationException($"类{type.Name}的主键[IsPk]特性未定义");
            }
            else
            {
                string sql = $"SELECT * FROM {tableAtrr.TableName} WHERE {colAtrr.ColumnName} = {ExType.ConvertSqliteString(idValue)};";
                using (var dataReader = ExecuteReader(sql))
                {
                    return dataReader.To<T>();
                }
            }
        }
        /// <summary>
        /// 查询一个表的所有数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="where"></param>
        /// <returns></returns>
        public List<T> FindAll<T>()
        {
            var type = typeof(T);
            var tableAtrr = type.GetTableAttribute();
            string sql = $"SELECT * FROM {tableAtrr.TableName};";
            using (var dataReader = ExecuteReader(sql))
            {
                return dataReader.ToList<T>();
            }
        }

        /// <summary>
        /// 带排序查询一个表的数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="orderBy">排序</param>
        /// <returns></returns>
        public List<T> FindAll<T>(Expression<Func<IQueryable<T>, IOrderedQueryable<T>>> orderBy) where T : class
        {
            var type = typeof(T);
            var tableAtrr = type.GetTableAttribute();
            string sql = $"SELECT * FROM {tableAtrr.TableName};";
            if (orderBy != null)
            {
                string orby = LambdaToSql.GetOrderBySql(orderBy);
                if (!string.IsNullOrWhiteSpace(orby))
                {
                    sql = $"SELECT * FROM {tableAtrr.TableName}  {orby};";
                }
                using (var dataReader = ExecuteReader(sql))
                {
                    return dataReader.ToList<T>();
                }
            }
            else
            {
                using (var dataReader = ExecuteReader(sql))
                {
                    return dataReader.ToList<T>();
                }
            }
        }

        /// <summary>
        /// 带条件查询一个表的数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="where"></param>
        /// <returns></returns>
        public List<T> Find<T>(Expression<Func<T, bool>> where) where T : class
        {
            var type = typeof(T);
            var tableAtrr = type.GetTableAttribute();

            var whereMoudel = LambdaToSql.GetWhereSql(where);
            string sql = $"SELECT * FROM {tableAtrr.TableName};";
            if (whereMoudel != null)
            {
                sql = $"SELECT * FROM {tableAtrr.TableName} {whereMoudel.WhereSql};";

                using (var dataReader = ExecuteReader(sql, whereMoudel.Parameters))
                {
                    return dataReader.ToList<T>();
                }
            }
            else
            {
                using (var dataReader = ExecuteReader(sql))
                {
                    return dataReader.ToList<T>();
                }

            }
        }

        /// <summary>
        /// 带条件查询一个表的数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="where">条件</param>
        /// <param name="orderBy">排序</param>
        /// <returns></returns>
        public List<T> Find<T>(Expression<Func<T, bool>> where, Expression<Func<IQueryable<T>, IOrderedQueryable<T>>> orderBy) where T : class
        {
            var type = typeof(T);
            var tableAtrr = type.GetTableAttribute();

            var whereMoudel = LambdaToSql.GetWhereSql(where);
            string sql = $"SELECT * FROM {tableAtrr.TableName};";
            if (whereMoudel != null)
            {
                string orby = LambdaToSql.GetOrderBySql(orderBy);
                if (!string.IsNullOrWhiteSpace(orby))
                {
                    sql = $"SELECT * FROM {tableAtrr.TableName} {whereMoudel.WhereSql} {orby};";
                }
                else
                {
                    sql = $"SELECT * FROM {tableAtrr.TableName} {whereMoudel.WhereSql};";
                }
                using (var dataReader = ExecuteReader(sql, whereMoudel.Parameters))
                {
                    return dataReader.ToList<T>();
                }
            }
            else
            {
                using (var dataReader = ExecuteReader(sql))
                {
                    return dataReader.ToList<T>();
                }

            }
        }

        #endregion


        #endregion

        #region 静态公有方法


        /// <summary>
        /// 获取插入的sql语句
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static StringBuilder GetInsertSql<T>(T entity) where T : class
        {
            var builder = new StringBuilder();
            var file = new List<string>();//字段
            var file_value = new List<string>();//值

            var tableName = string.Empty;
            ParseEntity(entity, (tableAttribute, columnAttribute, columnValue) =>
            {
                tableName = tableAttribute.TableName;
                file.Add(columnAttribute.ColumnName);//字段
                file_value.Add(columnValue);//值
            });
            if (file.Count > 0)
            {
                builder.AppendLine(
                   string.Format("INSERT INTO {0} ({1}) VALUES ({2});",
                   tableName,
                   string.Join(",", file),
                   string.Join(",", file_value))
                );
            }
            return builder;
        }
        /// <summary>
        /// 获取插入的sql语句
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static StringBuilder GetInsertSql<T>(IEnumerable<T> entity) where T : class
        {
            return CreatCollectionStringBuilder(entity, (t) => GetInsertSql(t));
        }

        /// <summary>
        /// 获取更新的sql语句
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static StringBuilder GetUpdateSql<T>(T entity) where T : class
        {
            var builder = new StringBuilder();
            var file_value = new List<string>();//值
            var where = string.Empty;
            var tableName = string.Empty;
            ParseEntity(entity, (tableAttribute, columnAttribute, columnValue) =>
            {
                tableName = tableAttribute.TableName;
                string k_v = $"{columnAttribute.ColumnName}={columnValue}";
                file_value.Add(k_v);
                if (columnAttribute.IsPk)
                {
                    where = k_v;
                }
            });
            if (file_value.Count > 0 && !string.IsNullOrWhiteSpace(where))
            {
                builder.AppendLine(
                    string.Format("UPDATE {0} SET {1}  WHERE {2};",
                    tableName,
                    string.Join(",", file_value),
                    where)
                );
            }
            return builder;
        }
        /// <summary>
        /// 获取更新的sql语句
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static StringBuilder GetUpdateSql<T>(IEnumerable<T> entity) where T : class
        {
            return CreatCollectionStringBuilder(entity, (t) => GetUpdateSql(t));
        }


        /// <summary>
        /// 获取添加或更新的sql语句
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static StringBuilder GetInsertOrUpdateSql<T>(T entity) where T : class
        {
            var builder = new StringBuilder();
            var file = new List<string>();//字段
            var file_value = new List<string>();//值

            var tableName = string.Empty;
            ParseEntity(entity, (tableAttribute, columnAttribute, columnValue) =>
            {
                tableName = tableAttribute.TableName;
                file.Add(columnAttribute.ColumnName);//字段
                file_value.Add(columnValue);//值
            });
            if (file.Count > 0)
            {
                builder.AppendLine(
                   string.Format("INSERT OR REPLACE INTO {0} ({1}) VALUES ({2});",
                   tableName,
                   string.Join(",", file),
                   string.Join(",", file_value))
                );
            }
            return builder;
        }
        /// <summary>
        /// 获取添加或更新的sql语句
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static StringBuilder GetInsertOrUpdateSql<T>(IEnumerable<T> entity) where T : class
        {
            return CreatCollectionStringBuilder(entity, (t) => GetInsertOrUpdateSql(t));
        }


        /// <summary>
        /// 获取删除的sql语句
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static StringBuilder GetDeleteSql<T>(T entity) where T : class
        {
            var builder = new StringBuilder();
            var tableName = string.Empty;
            ParseEntity(entity, (tableAttribute, columnAttribute, columnValue) =>
            {
                if (columnAttribute.IsPk)
                {
                    builder.AppendLine(string.Format("DELETE FROM {0} WHERE {1}={2};", tableAttribute.TableName, columnAttribute.ColumnName, columnValue));
                }
            });
            return builder;

        }
        /// <summary>
        /// 获取删除的sql语句
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static StringBuilder GetDeleteSql<T>(IEnumerable<T> entity) where T : class
        {
            return CreatCollectionStringBuilder(entity, (t) => GetDeleteSql(t));
        }
        #endregion

        #region 静态私有

        /// <summary>
        /// 创建sql集合语句
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        private static StringBuilder CreatCollectionStringBuilder<T>(IEnumerable<T> entity, Func<T, StringBuilder> func)
        {
            var builder = new StringBuilder();
            if (entity != null && entity.Any())
            {
                entity.ToList().ForEach(c =>
                {
                    if (func != null)
                    {
                        var tmp = func(c);
                        if (tmp != null && tmp.Length > 0)
                        {
                            builder.Append(tmp);
                        }
                    }
                });
            }
            return builder;
        }

        /// <summary>
        /// 解析实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="action"></param>
        private static void ParseEntity<T>(T entity, Action<TableAttribute, ColumnAttribute, string> action) where T : class
        {
            var tableAttribute = entity.GetTableAttribute();
            var columnAttribute = entity.GetColumnAttribute();

            var propertys = entity.GetType().GetProperties();
            var virtualproInfo = propertys.Where(p => p.GetMethod.IsVirtual).ToArray();
            if (propertys != null && propertys.Length > 0)
            {
                foreach (var proInfo in propertys)
                {
                    if (proInfo.CanRead && proInfo.CanWrite && !virtualproInfo.Contains(proInfo))
                    {
                        var colatt = columnAttribute.FirstOrDefault(c => c.FileName.Equals(proInfo.Name));
                        if (colatt != null && action != null)
                        {
                            action(tableAttribute, colatt, ExType.ConvertSqliteString(proInfo.GetValue(entity)));
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 解析实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="action"></param>
        private static void ParseEntity<T>(Action<TableAttribute, ColumnAttribute> action) where T : class
        {
            var type = typeof(T);
            var tableAttribute = type.GetTableAttribute();
            var columnAttribute = type.GetColumnAttribute();

            var propertys = type.GetProperties();
            var virtualproInfo = propertys.Where(p => p.GetMethod.IsVirtual).ToArray();
            if (propertys != null && propertys.Length > 0)
            {
                foreach (var proInfo in propertys)
                {
                    if (proInfo.CanRead && proInfo.CanWrite && !virtualproInfo.Contains(proInfo))
                    {
                        var colatt = columnAttribute.FirstOrDefault(c => c.FileName.Equals(proInfo.Name));
                        if (colatt != null && action != null)
                        {
                            action(tableAttribute, colatt);
                        }
                    }
                }
            }
        }


        #endregion

        #region 私有方法
        /// <summary>
        /// 生成创建表的语句
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        private StringBuilder GetCreatTableBuilder<T>() where T : class
        {
            var builder = new StringBuilder();
            var type = typeof(T);
            var fileProperty = new List<string>();

            var tableAttribute = type.GetTableAttribute();
            var columnAttribute = type.GetColumnAttribute();

            var propertys = type.GetProperties();
            var virtualproInfo = propertys.Where(p => p.GetMethod.IsVirtual).ToArray();
            if (propertys != null && propertys.Length > 0)
            {
                foreach (var proInfo in propertys)
                {
                    if (proInfo.CanRead && proInfo.CanWrite && !virtualproInfo.Contains(proInfo))
                    {
                        var colatt = columnAttribute.FirstOrDefault(c => c.FileName.Equals(proInfo.Name));
                        if (colatt != null)
                        {
                            //==============>[字段名]                                  数据类型                                                       是否是主键                       是否可以为空
                            var file = $"[{colatt.ColumnName}] {Enum.GetName(typeof(SqliteType), ExType.GetSqliteType(proInfo.PropertyType)).ToUpper()} {(colatt.IsPk ? "PRIMARY KEY" : "")} {(colatt.NotNull ? "NOT NULL" : "")}";
                            file = $"{file.TrimEnd()}";
                            fileProperty.Add(file);
                        }
                    }
                }
            }
            if (fileProperty.Count > 0 && !string.IsNullOrWhiteSpace(tableAttribute.TableName))
            {
                builder.AppendLine($@"CREATE TABLE IF NOT EXISTS [{tableAttribute.TableName}] ({string.Join(",", fileProperty)});").AppendLine();
            }
            return builder;
        }

        /// <summary>
        ///创建连接字符串
        /// </summary>
        /// <returns></returns>
        private SqliteConnection CreateSqliteConnection()
        {
            var directory = Path.GetDirectoryName(_connectionString);
            if (!string.IsNullOrWhiteSpace(directory) && !Directory.Exists(directory))
            {//当目录为空的时候 数据库文件则创建在当前运行目录
                Directory.CreateDirectory(directory);
            }
            var connection = new SqliteConnection($"Data Source={_connectionString}");
            connection.Open();

            return connection;

        }

        #endregion
    }


}
